import backtrader as bt
import talib


# talib识别三角形结构
class TrianglePatternStrategy(bt.Strategy):
    def __init__(self):
        self.close = self.datas[0].close
        self.high = self.datas[0].high
        self.low = self.datas[0].low

    def next(self):
        closes = self.close.get(size=self.data.buflen())
        highs = self.high.get(size=self.data.buflen())
        lows = self.low.get(size=self.data.buflen())

        upper_trendline = talib.LINEARREG_ANGLE(closes, timeperiod=len(closes)) > 0
        lower_trendline = talib.LINEARREG_ANGLE(closes, timeperiod=len(closes)) < 0

        # 假设三角形的条件为上下两条趋势线夹角逐渐变小且价格在一定范围内波动
        if upper_trendline and lower_trendline:
            print("可能出现三角形结构")


# 创建 Cerebro 实例
cerebro = bt.Cerebro()

# 添加数据
data = bt.feeds.YahooFinanceData(
    dataname="AAPL",
    fromdate=datetime.datetime(2020, 1, 1),
    todate=datetime.datetime(2023, 1, 1),
)
cerebro.adddata(data)

# 添加策略
cerebro.addstrategy(TrianglePatternStrategy)

# 运行回测
cerebro.run()
